$(document).ready(function($) {

    $(".gohistory").click(function(){
        window.history.go(-1);
    })

    /*左侧菜单*/
    var $window = $(window), $subnav = $("#subnav"), url;
    /*$window.resize(function(){
        $("#main").css("min-height", $window.height() - 130);
    }).resize();*/

    /* 左边菜单高亮 */
    url = window.location.pathname + window.location.search;
    url = url.replace(/(\/(p)\/\d+)|(&p=\d+)|(\/(id)\/\d+)|(&id=\d+)|(\/(group)\/\d+)|(&group=\d+)/, "");
    url = BASE_URL + url;
    $subnav.find("a[href='" + url + "']").parent().addClass("current");

    /* 左边菜单显示收起 */
    $("#subnav").on("click", "h3", function(){
        var $this = $(this);
        $this.find('.glyphicon').toggleClass('glyphicon-minus glyphicon-plus');
        $this.next().slideToggle("fast").siblings(".side-sub-menu:visible").
              prev("h3").find("i").addClass("glyphicon-plus").end().end().hide();
    });

    $("#subnav h3 a").click(function(e){e.stopPropagation()});

    //搜索
    $("#search").click(function(){
		var url = $(this).attr('url');
        var query  = $('.search-form').find('input').serialize();
        query = query.replace(/(&|^)(\w*?\d*?\-*?_*?)*?=?((?=&)|(?=$))/g,'');
        query = query.replace(/^&/g,'');
        if( url.indexOf('?')>0 ){
            url += '&' + query;
        }else{
            url += '?' + query;
        }
		window.location.href = url;
	});
	//回车搜索
	$(".search-input").keyup(function(e){
		if(e.keyCode === 13){
			$("#search").click();
			return false;
		}
	});

	//全选的实现
	$(".check-all").click(function(){
		$(".ids").prop("checked", this.checked);
	});
	$(".ids").click(function(){
		var option = $(".ids");
		option.each(function(i){
			if(!this.checked){
				$(".check-all").prop("checked", false);
				return false;
			}else{
				$(".check-all").prop("checked", true);
			}
		});
	});

    //ajax get请求
    $('.ajax-get').click(function(){
        var target;
        var that = this;
        if ( $(this).hasClass('confirm') ) {
            if(!confirm('确认要执行该操作吗?')){
                return false;
            }
        }
        if ( (target = $(this).attr('href')) || (target = $(this).attr('url')) ) {
            $.get(target).success(function(data){
                // return false;
                if (data.status==1) {
                    if (data.url) {
                        message_box.show('<h4>提示信息</h4>'+data.info+'页面即将自动跳转','success');
                    }else{
                        message_box.show('<h4>提示信息</h4>'+data.info,'success');
                    }
                    setTimeout(function(){
                        if (data.url) {
                            location.href=data.url;
                        }else{
                            location.reload();
                        }
                    },1500);
                }else{
                    message_box.show('<h4>提示信息</h4>'+data.info,'danger');
                    setTimeout(function(){
                        if (data.url) {
                            location.href=data.url;
                        }else{
                            location.reload();
                        }
                    },1500);
                }
            });

        }
        return false;
    });

    //ajax post submit请求
    $('.ajax-post').click(function(){
        var target,query,form;
        var target_form = $(this).attr('target-form');
        var that = this;
        var nead_confirm=false;
        if( ($(this).attr('type')=='submit') || (target = $(this).attr('href')) || (target = $(this).attr('url')) ){
            form = $('.'+target_form);

            if ($(this).attr('hide-data') === 'true'){//无数据时也可以使用的功能
            	form = $('.hide-data');
            	query = form.serialize();
            }else if (form.get(0)==undefined){
            	return false;
            }else if ( form.get(0).nodeName=='FORM' ){
                if ( $(this).hasClass('confirm') ) {
                    if(!confirm('确认要执行该操作吗?')){
                        return false;
                    }
                }
                if($(this).attr('url') !== undefined){
                	target = $(this).attr('url');
                }else{
                	target = form.get(0).action;
                }
                query = form.serialize();
            }else if( form.get(0).nodeName=='INPUT' || form.get(0).nodeName=='SELECT' || form.get(0).nodeName=='TEXTAREA') {
                form.each(function(k,v){
                    if(v.type=='checkbox' && v.checked==true){
                        nead_confirm = true;
                    }
                })
                if ( nead_confirm && $(this).hasClass('confirm') ) {
                    if(!confirm('确认要执行该操作吗?')){
                        return false;
                    }
                }
                query = form.serialize();
            }else{
                if ( $(this).hasClass('confirm') ) {
                    if(!confirm('确认要执行该操作吗?')){
                        return false;
                    }
                }
                query = form.find('input,select,textarea').serialize();
            }
            if ( query == '' ) {
                message_box.show('<h4>提示信息</h4>请选择要操作项','danger');
                return false;
            };
            $(that).addClass('disabled').attr('autocomplete','off').prop('disabled',true);
            

            $.post(target,query).success(function(data){
                // return false;
                if (data.status==1) {
                    if (data.url) {
                        message_box.show('<h4>提示信息</h4>'+data.info+'页面即将自动跳转','success');
                    }else{
                        message_box.show('<h4>提示信息</h4>'+data.info,'success');
                    }
                    setTimeout(function(){
                        if (data.url) {
                            location.href=data.url;
                        }else{
                            location.reload();
                        }
                    },1500);
                }else{
                    message_box.show('<h4>提示信息</h4>'+data.info,'danger');
                    setTimeout(function(){
                        if (data.url) {
                            location.href=data.url;
                        }else{
                            location.reload();
                        }
                    },1500);
                }
            });
        }
        return false;
    });
	
    /**
     * 创建专利产品对官费的操作
     */
    $("#office_price input").on('click',function(){
        // console.log( $(this).data('role') );
        //检测是否被选中
        if ( $(this).prop('checked') ) {
             //获取当前复选框文本
            var checkbox_text = $(this).data('role');
            //获取当前复选框的值
            var checkbox_val  = $(this).val();
            //在节点中新增html
            var html =  "<li id='"+checkbox_val+"'>";
                html += "<label>"+checkbox_text+":</label>";
                html += "<div class='input-group'>";
                html += "<div class='input-group-addon'>￥</div>";
                html += "<input type='text' data-role="+checkbox_text+" name='office["+checkbox_val+"]' class='form-control' onblur='check_office(this)'>";
                html += "<div class='input-group-addon'>.00元</div>";
                html += "</div>";
                html += "</li>";
                $(html).prependTo("#office_box");
        }else{
             //获取当前复选框的值
            var checkbox_val  = $(this).val();
            //移除新增的html
            $("#"+checkbox_val).remove();
        }
    })

    //订单详情查看联系人
    $('[data-toggle="popover"]').popover();//初始化popover
    $(".popover1").popover({
        html: true,
        placement: 'bottom',
        title: '查看联系人',
        content: function(){
            var order_id  = $(this).data('id');
            var div_id =  "tmp-id-" + order_id;
            var geturl = $(this).data('url');
            return details_in_popup(div_id, order_id, geturl);
        }
    })

    function details_in_popup(div_id, order_id, url){
        $.post(url, {'order_id':order_id}, function(res){
            if ( res.status > 0 ) {
                var show_html = "<dl><dt>称呼:</dt>";
                    show_html += "<dd>"+ res.info.real_name+"</dd>";
                    show_html += "<dt>手机：</dt>";
                    show_html += "<dd>"+res.info.mobile+"</dd>";
                    show_html += "<dt>QQ：</dt>";
                    show_html += "<dd>"+res.info.qq+"</dd>";
                    show_html += "<dt>微信：</dt>";
                    show_html += "<dd>"+res.info.weixin+"</dd>";
                    show_html +="</dl>";
               $('#'+div_id).html(show_html);
            }else{
                $('#'+div_id).html("<p class='text-danger'>获取内容失败</p>");
            }
        })
        return '<div id="'+ div_id +'">Loading...</div>';
    }




})


/**
 * 改变缩略图大小
 * @Author Baip
 */
function DrawImage(ImgD,FitWidth,FitHeight){
    var image=new Image();
    image.src=ImgD.src;
    if(image.width>0 && image.height>0)
    {
        if(image.width/image.height>= FitWidth/FitHeight)
        {
            if(image.width>FitWidth)
            {
                ImgD.width=FitWidth;
                ImgD.height=(image.height*FitWidth)/image.width;
            }
            else
            {
                ImgD.width=image.width;
                ImgD.height=image.height;
            }
        }
        else
        {
            if(image.height>FitHeight)
            {
                ImgD.height=FitHeight;
                ImgD.width=(image.width*FitHeight)/image.height;
            }
            else
            {
                ImgD.width=image.width;
                ImgD.height=image.height;
            }
        }
    }
}

// 缩放图片
function resizeImg(node,isSmall){
    if(!isSmall){
        $(node).height($(node).height()*1.2);
    } else {
        $(node).height($(node).height()*0.8);
    }
}

/**
 * 设置表单的值
 * @param {[type]} name  [description]
 * @param {[type]} value [description]
 */
function setValue (name, value){
        var first = name.substr(0,1), input, i = 0, val;
        if(value === "") return;
        if("#" === first || "." === first){
            input = $(name);
        } else {
            input = $("[name='" + name + "']");
        }

        if(input.eq(0).is(":radio")) { //单选按钮
            input.filter("[value='" + value + "']").each(function(){this.checked = true});
        } else if(input.eq(0).is(":checkbox")) { //复选框
            if(!$.isArray(value)){
                val = new Array();
                val[0] = value;
            } else {
                val = value;
            }
            for(i = 0, len = val.length; i < len; i++){
                input.filter("[value='" + val[i] + "']").each(function(){this.checked = true});
            }
        } else {  //其他表单选项直接设置值
            input.val(value);
        }
}

//导航高亮
function highlight_subnav(url){
    $('.side-sub-menu').find('a[href="'+url+'"]').closest('li').addClass('current');
}

/**
 * 检测官费价格
 * @param  {[type]} obj [description]
 * @return {[type]}     [description]
 */
function check_office(obj){
    var office_val = $(obj).val();
    var office_text = $(obj).data('role');
    if ( office_val == '' ) {
       message_box.show('<h4>提示信息</h4>请填写'+office_text+'价格','error');
       $(obj).focus().val('');
       return false;
    }else if ( !reg_numer(office_val) ) {
       message_box.show('<h4>提示信息</h4>'+office_text+'价格必须为正整数','error');
       $(obj).focus().val('');
       return false;
    }
    return true;
}